package org.chen.wordwave.act.game;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.hjq.toast.Toaster;

import org.chen.wordwave.Api.ApiClient;
import org.chen.wordwave.Api.ApiService;
import org.chen.wordwave.R;
import org.chen.wordwave.bean.Configs;
import org.chen.wordwave.bean.SignIn;
import org.chen.wordwave.bean.UserInfo;
import org.chen.wordwave.init.WordInit;
import org.chen.wordwave.tools.user.UserUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class GameBoard extends AppCompatActivity implements View.OnClickListener {

    private TextView sTitleTxt, scoreTxt, letter1, letter2, letter3, letter4, letter5;
    private ProgressBar pb;
    private Button letterButt1, letterButt2, letterButt3, letterButt4, letterButt5;

    private Timer gameTimer;
    private float progress;
    private List<String> wordsArray;
    private List<String> charArray;
    private String wordStr = "";
    private int tapsCount = 0;
    private String firstWord = "";
    private String secondWord = "";
    private String thirdWord = "";
    private String wordByCharacters = "";
    private int randomCircle = 0;
    private Button [] letterButtons;
    private TextView [] letterTxts;
    private MediaPlayer mp;

    @Override
    protected void onStart() {
        super.onStart();

        // 重置分数
        Configs.score = 0;
        scoreTxt.setText(String.valueOf(Configs.score));


        // 设置progressBar并启动游戏计时器
        pb = (ProgressBar)findViewById(R.id.gbProgressBar);
        progress = 0;
        pb.setProgress(0);
        startGameTimer();


        // 获取一个随机的字母圆圈
        Random r = new Random();
        randomCircle = r.nextInt(Configs.circlesArray.length);


        // 重置抽头计数
        tapsCount = -1;


        // 从单词字符串数组中获取一个随机单词
        getRandomWord();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game_board_act);
        super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

        // 获取单词的列表数组
        String [] wordsArr = getResources().getStringArray(R.array.words);
        wordsArray = new ArrayList<String>(Arrays.asList(wordsArr));

        sTitleTxt = (TextView)findViewById(R.id.gbScoreTxt);
        scoreTxt = (TextView)findViewById(R.id.gbPointsTxt);
        scoreTxt.setTypeface(Configs.juneGull);

        letter1 = (TextView)findViewById(R.id.letter1);
        letter1.setTypeface(Configs.juneGull);
        letter2 = (TextView)findViewById(R.id.letter2);
        letter2.setTypeface(Configs.juneGull);
        letter3 = (TextView)findViewById(R.id.letter3);
        letter3.setTypeface(Configs.juneGull);
        letter4 = (TextView)findViewById(R.id.letter4);
        letter4.setTypeface(Configs.juneGull);
        letter5 = (TextView)findViewById(R.id.letter5);
        letter5.setTypeface(Configs.juneGull);

        letterButt1 = (Button)findViewById(R.id.letterButt1);
        letterButt1.setTypeface(Configs.juneGull);
        letterButt1.setOnClickListener(this);
        letterButt2 = (Button)findViewById(R.id.letterButt2);
        letterButt2.setTypeface(Configs.juneGull);
        letterButt2.setOnClickListener(this);
        letterButt3 = (Button)findViewById(R.id.letterButt3);
        letterButt3.setTypeface(Configs.juneGull);
        letterButt3.setOnClickListener(this);
        letterButt4 = (Button)findViewById(R.id.letterButt4);
        letterButt4.setTypeface(Configs.juneGull);
        letterButt4.setOnClickListener(this);
        letterButt5 = (Button)findViewById(R.id.letterButt5);
        letterButt5.setTypeface(Configs.juneGull);
        letterButt5.setOnClickListener(this);

        // 制作字母按钮阵列
        letterButtons = new Button[5];
        letterButtons[0] = letterButt1;
        letterButtons[1] = letterButt2;
        letterButtons[2] = letterButt3;
        letterButtons[3] = letterButt4;
        letterButtons[4] = letterButt5;


        // 在顶部做一个字母数组
        letterTxts = new TextView[5];
        letterTxts[0] = letter1;
        letterTxts[1] = letter2;
        letterTxts[2] = letter3;
        letterTxts[3] = letter4;
        letterTxts[4] = letter5;

        Button resetButt = (Button)findViewById(R.id.gbResetButt);
        resetButt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetWord();

                playSound("resetWord.mp3");
            }});


        Button backButt = (Button)findViewById(R.id.gbBackButt);
        backButt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gameTimer.cancel();
                finish();
            }});


    }


    void resetLetterButtons() {

        for (int i = 0; i<5; i++) {
            letterButtons[i].setEnabled(true);
            letterButtons[i].setBackgroundResource(Configs.circlesArray[randomCircle]);
            letterButtons[i].setTextColor(Color.parseColor("#ffffff"));
        }

        // 重置字母text顶部的视图
        resetLettersTxt();
    }


    void resetLettersTxt() {
        for (int i = 0; i<5; i++) {
            letterTxts[i].setText("");
            letterTxts[i].setBackgroundResource(R.drawable.circle_corner_white);
        }
    }


    void getRandomWord() {

        // 获取一个随机的字母圆圈
        Random r = new Random();
        randomCircle = r.nextInt(Configs.circlesArray.length);
        // Log.i("log-", "RAND CIRCLE: " + randomCircle);


        // 从字符串数组中获取一个随机单词
        wordStr = wordsArray.get(new Random().nextInt(wordsArray.size()));
        Log.i("log-", "RANDOM WORD: " + wordStr);


        // 获取单词数组（如果有多个单词
        Configs.stringsArray = new ArrayList<String>();

        if (wordStr.contains(".")) {
            String[] one = wordStr.split(Pattern.quote("."));
            Configs.stringsArray.addAll(Arrays.asList(one));
            Log.i("log-", "\n\nWORDS ARRAY: " + Configs.stringsArray);

        } else {
            Log.i("log-", "SINGLE WORD: " + wordStr);
            Configs.stringsArray.add(wordStr);
        }



        // 获取完整的单词作为字符列表
        charArray = new ArrayList<String>();
        String[] chArr = wordStr.split("");
        int length = Math.min(chArr.length, 6); // 获取字符数组的长度和6中较小的一个
        charArray.addAll(Arrays.asList(chArr).subList(0, length));
        Log.i("log-", "CHARS ARRAY: " + charArray);

        getRandomChar();
    }


    void getRandomChar() {

        // 获取在游戏板上显示字符的随机组合
        Random r = new Random();
        int randomCombination = r.nextInt(3);

        switch (randomCombination) {
            case 0:
                letterButtons[1].setText(charArray.get(0));
                letterButtons[0].setText(charArray.get(1));
                letterButtons[4].setText(charArray.get(2));
                letterButtons[2].setText(charArray.get(3));
                letterButtons[3].setText(charArray.get(4));
                break;

            case 1:
                letterButtons[3].setText(charArray.get(0));
                letterButtons[0].setText(charArray.get(1));
                letterButtons[4].setText(charArray.get(2));
                letterButtons[1].setText(charArray.get(3));
                letterButtons[2].setText(charArray.get(4));
                break;

            case 2:
                letterButtons[4].setText(charArray.get(0));
                letterButtons[1].setText(charArray.get(1));
                letterButtons[0].setText(charArray.get(2));
                letterButtons[3].setText(charArray.get(3));
                letterButtons[2].setText(charArray.get(4));
                break;
        }


        // 调用重置Word功能
        resetWord();

    }

    void resetWord() {
        // 重置抽头计数
        tapsCount = -1;

        // 重置逐字逐句
        wordByCharacters = "";

        // 重置字母按钮
        resetLetterButtons();

        // 重置顶部字母
        resetLettersTxt();
    }



    void startGameTimer() {
        // 计算每秒钟增加的值
        final float progressIncreasePerSecond = 100f / Configs.roundTime;

        gameTimer =  new Timer();
        gameTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 增加进度
                        progress += progressIncreasePerSecond;
                        // 更新进度条
                        pb.setProgress((int) progress);

                        // 如果时间结束，游戏结束
                        if (progress >= 100) {
                            gameTimer.cancel();
                            gameOver();
                        }
                    }
                });
            }
        }, 0, 1000); // 每秒钟执行一次
    }



    // 更新游戏计时器
    void updateTimer() {
        gameTimer.cancel();
        pb.setProgress((int) progress);
        startGameTimer();
    }


    // - 点击字母按钮
    @Override
    public void onClick(View v) {
        Button lettButt = (Button)findViewById(v.getId());

        tapsCount = tapsCount+1;
        // Log.i("log-", "TAPS COUNT: " + tapsCount);

        // 设置字母
        letterTxts[tapsCount].setText(lettButt.getText().toString() );
        letterTxts[tapsCount].setBackgroundResource(Configs.circlesArray[randomCircle]);

        // 更改按钮状态
        lettButt.setBackgroundResource(R.drawable.circle_corner_white);
        lettButt.setTextColor(Color.parseColor("#999999"));
        lettButt.setEnabled(false);

        // 按显示的字符创建字符串
        wordByCharacters = wordByCharacters + letterTxts[tapsCount].getText().toString();
        Log.i("log-", "WORD BY CHARS: " + wordByCharacters);


        // 你已经点击了所有按钮，请检查你的结果
        if (tapsCount == 4) { checkResult(); }

        playSound("buttTapped.mp3");

    }

    // - 检查结果
    void checkResult() {

        firstWord = Configs.stringsArray.get(0);

        if (Configs.stringsArray.size() == 2) {
            secondWord = Configs.stringsArray.get(1);
        }
        if (Configs.stringsArray.size() == 3) {
            secondWord = Configs.stringsArray.get(1);
            thirdWord = Configs.stringsArray.get(2);
        }

        if (wordByCharacters.matches(firstWord) ||
                wordByCharacters.matches(secondWord) ||
                wordByCharacters.matches(thirdWord) ) {

            playSound("rightWord.mp3");

            Configs.score = Configs.score + 10;
            scoreTxt.setText(String.valueOf(Configs.score));


            // 更新游戏计时器
            progress = progress - Configs.bonusProgress;
            // 增加5秒
            progress += 5;
            if (progress > 100) progress = 100; // 确保进度不超过 100%
            updateTimer();


            // 获取一个新的随机单词
            getRandomWord();


            // 这个词错了
        } else {
            wordByCharacters = "";
            getRandomChar();

            playSound("resetWord.mp3");
        }
    }


    // - 游戏结束
    void gameOver() {

        if (Configs.score >= 100){
            new Thread(() -> {
                UserInfo userInfo = UserUtils.getUserInfo(this);
                SignIn signIn = new SignIn();
                signIn.setMember(userInfo.isMember());
                signIn.setPoints(userInfo.getPoints() + 100);
                signIn.setEmail(WordInit.userInfo.getEmail());
                ApiService apiService = ApiClient.getClient(this).create(ApiService.class);
                apiService.gift(signIn).enqueue(new Callback<SignIn>() {
                    @Override
                    public void onResponse(Call<SignIn> call, Response<SignIn> response) {
                        Toaster.show(getString(R.string.prize_100,100));
                    }

                    @Override
                    public void onFailure(Call<SignIn> call, Throwable t) {
                        Toaster.show(getString(R.string.prize_100_error));
                    }
                });
            }).start();
        }

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(GameBoard.this);
        Configs.bestScore = prefs.getInt("bestScore", Configs.bestScore);


        if (Configs.bestScore <= Configs.score) {
            Configs.bestScore = Configs.score;
            prefs.edit().putInt("bestScore", Configs.bestScore).apply();
        }


        playSound("gameOver.mp3");


        startActivity(new Intent(GameBoard.this, GameOver.class));
    }


    //- 播放声音
    void playSound(String soundName) {
        try {

            MediaPlayer mp = new MediaPlayer();

            AssetFileDescriptor afd = getAssets().openFd("sounds/" + soundName);
            mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());

            mp.prepare();
            mp.setVolume(1f, 1f);
            mp.setLooping(false);
            mp.start();

            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.release();
                }});

        } catch (Exception e) { Log.e("e",e.toString()); }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        gameTimer.cancel();
    }
}
